package com.yqg.protection.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yqg.protection.entity.*;
import com.yqg.protection.mapper.UserMapper;
import com.yqg.protection.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

/**
 * projectName:xf-service1
 * author:zxf
 * time:2024/10/10 17:03
 * description:
 */
@Component
@Slf4j
public class TimedTasks {

    @Value("${data.upload.path}")
    private String dataUploadPath;

    @Autowired
    IFireSysDataService fireSysDataService;

    @Autowired
    IEquipmentInputStoreService equipmentInputStoreService;

    @Autowired
    ISimInputStoreService simInputStoreService;

    @Autowired
    IAnnounceService announceService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    IOrganizationService organizationService;

    @Autowired
    IRecordOperateService recordOperateService;

    @Resource
    private ITemporaryDataService temporaryDataService;

    @Resource
    private IHistoryFireCockService historyFireCockService;

    @Resource
    private ISdf300HistoryDataService sdf300HistoryDataService;

    @Resource
    private IHistoryDqService historyDqService;

    @Resource
    private IHistoryJhService historyJhService;

    @Resource
    private IHistoryLsService historyLsService;

    @Resource
    private IHistoryQgService historyQgService;

    @Resource
    private IHistoryYgService historyYgService;

    //定时删除日志文件 0 0 0 1 * ?
    @Scheduled(cron = "0 0 0 1 * ?")
    public void deleteData() {
        File directory = new File(dataUploadPath);
        LocalDate now = LocalDate.now();
        // 获取上个月的第一天
        LocalDate firstDayOfLastMonth = now.with(TemporalAdjusters.firstDayOfMonth()).minusMonths(1);
        // 获取上个月第一天的0点
        LocalDateTime midnightOfFirstDayLastMonth = LocalDateTime.of(firstDayOfLastMonth, LocalTime.MIN);
        ZoneId zoneId = ZoneId.systemDefault(); // 系统默认时区
        // 转换为ZonedDateTime
        ZonedDateTime zonedDateTime = midnightOfFirstDayLastMonth.atZone(zoneId);
        // 转换为毫秒数
        long millis = zonedDateTime.toInstant().toEpochMilli();
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.lastModified() < millis) {
                    file.delete();
                }
            }
        }
    }

    //定时删除FireSysData数据 0 0 0 1/1 * ?
    @Scheduled(cron = "0 0 0 1/1 * ?")
    public void deleteFireSysData() {
        LocalDate now = LocalDate.now();
        // 获取上一天
        LocalDate firstDayOfLastDay = now.minusDays(1);
        // 获取上一天的0点
        LocalDateTime midnightOfFirstDayLastDay = LocalDateTime.of(firstDayOfLastDay, LocalTime.MIN);
        LambdaQueryWrapper<FireSysData> fireSysDataQueryWrapper = new LambdaQueryWrapper<>();
        fireSysDataQueryWrapper.lt(FireSysData::getEnterTime, midnightOfFirstDayLastDay);
        fireSysDataService.remove(fireSysDataQueryWrapper);
    }

    //定时删除操作日志文件 0 0 0 1 * ?
    @Scheduled(cron = "0 0 0 1 * ?")
    public void deleteRecordOperate() {
        LocalDate now = LocalDate.now();
        // 获取上个月的第一天
        LocalDate firstDayOfLastMonth = now.with(TemporalAdjusters.firstDayOfMonth()).minusMonths(1);
        // 获取上个月第一天的0点
        LocalDateTime midnightOfFirstDayLastMonth = LocalDateTime.of(firstDayOfLastMonth, LocalTime.MIN);
        LambdaQueryWrapper<RecordOperate> recordOperateQueryWrapper = new LambdaQueryWrapper<>();
        recordOperateQueryWrapper.lt(RecordOperate::getCreatedTime, midnightOfFirstDayLastMonth);
        recordOperateService.remove(recordOperateQueryWrapper);
    }

    //定时删除history_fire_cock,sdf300_history_data,history_dq,······  0 0 0 1 * ?
    @Scheduled(cron = "0 0 0 1 * ?")
    public void deleteHistory() {
        LocalDate now = LocalDate.now();
        // 获取上个月的第一天
        LocalDate firstDayOfLastMonth = now.with(TemporalAdjusters.firstDayOfMonth()).minusMonths(1);
        // 获取上个月第一天的0点
        LocalDateTime midnightOfFirstDayLastMonth = LocalDateTime.of(firstDayOfLastMonth, LocalTime.MIN);
        LambdaQueryWrapper<HistoryFireCock> historyFireCockLambdaQueryWrapper = new LambdaQueryWrapper<>();
        historyFireCockLambdaQueryWrapper.lt(HistoryFireCock::getSendTime, midnightOfFirstDayLastMonth);
        historyFireCockService.remove(historyFireCockLambdaQueryWrapper);
        LambdaQueryWrapper<Sdf300HistoryData> sdf300HistoryDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sdf300HistoryDataLambdaQueryWrapper.lt(Sdf300HistoryData::getSendTime, midnightOfFirstDayLastMonth);
        sdf300HistoryDataService.remove(sdf300HistoryDataLambdaQueryWrapper);
        LambdaQueryWrapper<HistoryDq> historyDqLambdaQueryWrapper = new LambdaQueryWrapper<>();
        historyDqLambdaQueryWrapper.lt(HistoryDq::getSendTime, midnightOfFirstDayLastMonth);
        historyDqService.remove(historyDqLambdaQueryWrapper);
        LambdaQueryWrapper<HistoryJh> historyJhLambdaQueryWrapper = new LambdaQueryWrapper<>();
        historyJhLambdaQueryWrapper.lt(HistoryJh::getSendTime, midnightOfFirstDayLastMonth);
        historyJhService.remove(historyJhLambdaQueryWrapper);
        LambdaQueryWrapper<HistoryLs> historyLsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        historyLsLambdaQueryWrapper.lt(HistoryLs::getSendTime, midnightOfFirstDayLastMonth);
        historyLsService.remove(historyLsLambdaQueryWrapper);
        LambdaQueryWrapper<HistoryQg> historyQgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        historyQgLambdaQueryWrapper.lt(HistoryQg::getSendTime, midnightOfFirstDayLastMonth);
        historyQgService.remove(historyQgLambdaQueryWrapper);
        LambdaQueryWrapper<HistoryYg> historyYgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        historyYgLambdaQueryWrapper.lt(HistoryYg::getSendTime, midnightOfFirstDayLastMonth);
        historyYgService.remove(historyYgLambdaQueryWrapper);
    }

    //公告更新 每月1,15号 0 0 0 1,15 * ?
    @Scheduled(cron = "0 0 0 1,15 * ?")
    @Transactional(rollbackFor = Exception.class)
    public void sendAnnounce() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<EquipmentInputStore> equipmentInputStoreQueryWrapper = new LambdaQueryWrapper<>();
        equipmentInputStoreQueryWrapper.eq(EquipmentInputStore::getIsDelete, 0);
        equipmentInputStoreQueryWrapper.lt(EquipmentInputStore::getEndTime, now.plusMonths(1L));
        List<EquipmentInputStore> equipmentInputStores = equipmentInputStoreService.list(equipmentInputStoreQueryWrapper);
        ArrayList<Announce> announces = new ArrayList<>();
        for (EquipmentInputStore equipmentInputStore : equipmentInputStores) {
            Organization organization = organizationService.getById(equipmentInputStore.getOrganization());
            List<Long> userIds = userMapper.getAllUsersByOrganId(organization.getLevel(), organization.getCountry(),
                    organization.getScTeam(), organization.getFcTeam(),
                    organization.getFbTeam(), organization.getCommunity(),
                    organization.getBuilding(), organization.getUnit(),
                    organization.getFloor(), organization.getRoom(),
                    equipmentInputStore.getClientId());
            for (Long userId : userIds) {
                Announce announce = new Announce();
                announce.setUserId(userId);
                announce.setClientId(equipmentInputStore.getClientId());
                announce.setType("0");
                announce.setEquipOrSimId(equipmentInputStore.getId());
                if (now.isAfter(equipmentInputStore.getEndTime())) {
                    announce.setContent("设备号为" + equipmentInputStore.getEquipmentId() + "的服务已过期，请及时续费！");
                } else {
                    announce.setContent("设备号为" + equipmentInputStore.getEquipmentId() + "的服务即将过期，请及时续费！");
                }
                announce.setCreateTime(LocalDateTime.now());
                announce.setState("0");
                announces.add(announce);
            }
        }
//        LambdaQueryWrapper<SimInputStore> simInputStoreQueryWrapper = new LambdaQueryWrapper<>();
//        simInputStoreQueryWrapper.eq(SimInputStore::getIsDelete, 0);
//        simInputStoreQueryWrapper.eq(SimInputStore::getState, "1");
//        simInputStoreQueryWrapper.lt(SimInputStore::getTime, now.plusMonths(1L));
//        List<SimInputStore> simInputStores = simInputStoreService.list(simInputStoreQueryWrapper);
//        for (SimInputStore simInputStore : simInputStores) {
//            Organization organization = organizationService.getById(simInputStore.getOrganization());
//            List<Long> userIds = userMapper.getAllUsersByOrganId(organization.getLevel(), organization.getCountry(),
//                    organization.getScTeam(), organization.getFcTeam(),
//                    organization.getFbTeam(), organization.getCommunity(),
//                    organization.getBuilding(), organization.getUnit(),
//                    organization.getFloor(), organization.getRoom(),
//                    simInputStore.getClientId());
//            for (Long userId : userIds) {
//                Announce announce = new Announce();
//                announce.setUserId(userId);
//                announce.setClientId(simInputStore.getClientId());
//                announce.setType("1");
//                announce.setEquipOrSimId(simInputStore.getId());
//                if (now.isAfter(simInputStore.getTime())) {
//                    announce.setContent("卡号为" + simInputStore.getSimId() + "的套餐已过期，请及时续费！");
//                } else {
//                    announce.setContent("卡号为" + simInputStore.getSimId() + "的套餐即将过期，请及时续费！");
//                }
//                announce.setCreateTime(LocalDateTime.now());
//                announce.setState("0");
//                announces.add(announce);
//            }
//        }
        announceService.saveBatch(announces);
    }

//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Transactional(rollbackFor = Exception.class)
    public void setTemporaryData() {
        LambdaQueryWrapper<EquipmentInputStore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(EquipmentInputStore::getId, 480);
        List<EquipmentInputStore> list = equipmentInputStoreService.list(queryWrapper);
        ArrayList<TemporaryData> temporaryDatas = new ArrayList<>();
        for (EquipmentInputStore equipmentInputStore:list) {
            TemporaryData temporaryData = new TemporaryData();
            temporaryData.setEquipmentId(equipmentInputStore.getEquipmentId());
            temporaryData.setUpTime(LocalDateTime.now().plusYears(25));
            temporaryDatas.add(temporaryData);
        }
        temporaryDataService.saveBatch(temporaryDatas);
    }
}
